#!/usr/bin/env python
# -*- coding: utf-8 -*-
# pip install prettytable
import time
from datetime import datetime
from threading import Timer

# 设备ID、Key
Device = [
    ["687974577", "85tkrZV4fAYNvj2JYuNZKM8=t=g="],  # 道路：车流量、排队长度、延误时间
    ["687974754", "7JCJx1P8NOvh=OxHAhUkwFL8iHc="],  # 路口：倒计时、预测配时
]


class update_OneNet:
    def __init__(self):
        self.device_id = ""
        self.api_key = ""
        self.post_data = []
        self.get_data = []

    # 显示获取数据
    def show_get_data(self):
        # noinspection PyBroadException
        try:
            # 使用表格美化显示数据
            import prettytable as pt
            tb = pt.PrettyTable()
            tb.field_names = ["id", "update_at", "current_value"]
            for index, element in enumerate(self.get_data):
                ID = str(element.get('id', ''))
                update_at = str(element.get('update_at', ''))
                current_value = str(element.get('current_value', ''))
                tb.add_row([ID, update_at, current_value])
            print(tb)
        except Exception:
            # 直接显示数据
            for index, element in enumerate(self.get_data):
                ID = str(element.get('id', ''))
                update_at = str(element.get('update_at', ''))
                current_value = str(element.get('current_value', ''))
                print(ID, update_at, current_value)

    # 上传函数
    @staticmethod
    def OneNet_post_data(info):
        import urllib.request as req
        import json
        url = "https://api.heclouds.com/devices/" + info[0] + '/datapoints'
        headers = {'api-key': info[1]}
        streams = []
        for index, element in enumerate(info[2]):
            streams.append({"id": element[0], "datapoints": [{"value": element[1]}]})
        data = json.dumps({"datastreams": streams}).encode("utf-8")
        request = json.loads((req.urlopen(req.Request(url, data, headers=headers))).read())
        return request

    # 获取函数
    @staticmethod
    def OneNet_get_data(info):
        import urllib.request as req
        import json
        url = "http://api.heclouds.com/devices/" + info[0] + "/datastreams"
        headers = {'api-key': info[1]}
        request = json.loads((req.urlopen(req.Request(url, headers=headers))).read())
        data = request.pop('data')
        return data, request

    # 准备待上传数据
    def prepare_post_data(self, idx, num):
        import random
        self.post_data = []
        if idx == 0:
            # 车流量、排队长度、延误时间数据
            for i in range(num):
                flow = random.randint(0, 100)
                queue = random.randint(0, 100)
                dealy = random.randint(0, 100)
                self.post_data.append(["road" + str(i + 1), "%s, %s, %s" % (flow, queue, dealy)])
        else:
            # 信号灯倒计时、预测配时数据
            for i in range(num):
                r = random.randint(0, 100)
                g = random.randint(0, 100)
                y = random.randint(0, 100)
                pr = random.randint(0, 100)
                pg = random.randint(0, 100)
                py = random.randint(0, 100)
                self.post_data.append(["cross" + str(i + 1), "%s, %s, %s, %s, %s, %s" %
                                       (r, g, y, pr, pg, py)])

    # 间隔时间上传数据函数
    def interval_post_data(self, dev, idx, num, sec):
        self.device_id = dev[idx][0]
        self.api_key = dev[idx][1]
        self.prepare_post_data(idx, num)
        self.OneNet_post_data([self.device_id, self.api_key, self.post_data])
        t = Timer(sec, self.interval_post_data, (dev, idx, num, sec,))
        t.start()

    # 间隔时间获取数据函数
    def interval_get_data(self, dev, idx, sec):
        self.device_id = dev[idx][0]
        self.api_key = dev[idx][1]
        self.get_data, reply = self.OneNet_get_data([self.device_id, self.api_key])
        self.show_get_data()
        t = Timer(sec, self.interval_get_data, (dev, idx, sec,))
        t.start()


if __name__ == '__main__':
    while True:
        now_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        print(now_time)
        if now_time[-1] == "0":
            print(now_time, "开始上传数据")
            break
        else:
            time.sleep(1)
    update = update_OneNet()
    # 上传道路状态数据
    update.interval_post_data(Device, 0, 57, 5)
    # 获取路口信号灯配时数据
    update.interval_get_data(Device, 0, 5)

    # 上传路口信号灯配时数据
    update.interval_post_data(Device, 1, 16, 5)
    # 获取道路状态数据
    update.interval_get_data(Device, 1, 5)
